package org.jspresso.framework.application.backend.action.module;

import java.util.List;
import java.util.Map;

import org.jspresso.framework.action.IActionHandler;
import org.jspresso.framework.application.backend.BackendControllerHolder;
import org.jspresso.framework.application.model.Module;
import org.jspresso.framework.model.component.IComponent;
import org.jspresso.framework.model.descriptor.BasicRepeaterModelDescriptor;
import org.jspresso.framework.model.descriptor.IComponentDescriptor;

public class AddCollectionPropertyAsBeanSubModuleAction extends AddBeanAsSubModuleAction {
  @Override
  public boolean execute(IActionHandler actionHandler, Map<String, Object> context) {
    
    List<?> selectedCollection = getActionParameter(context);
    if (selectedCollection == null) {
      return false;
    }
    
    Module moduleToSelect = null;
    for (Object nextSelectedModuleObject : selectedCollection) {
      if(nextSelectedModuleObject instanceof IComponent) {
        
        
        preSelectModuleObject(nextSelectedModuleObject, context);
        
        IComponentDescriptor itemDescriptor = getBackendController(context).getEntityFactory().getComponentDescriptor(((IComponent)nextSelectedModuleObject).getComponentContract());
        
        Module parentModule = findDestinationModule(nextSelectedModuleObject, context);
        IComponentDescriptor<?> beanComponentDescriptor = new BasicRepeaterModelDescriptor(itemDescriptor, getBackendController(context).getEntityFactory().getComponentDescriptor(itemDescriptor.getPropertyDescriptor("segments").getModelType()), selectedCollection.size());
        
        List<Module> childModules = parentModule.getSubModules();
        Module newSubModule = null;
        
        Module nextSubModule = createChildModule(parentModule, beanComponentDescriptor, selectedCollection, context);
        int nextSubModuleIndex = -1;
        if (childModules != null) {
          nextSubModuleIndex = childModules.indexOf(nextSubModule);
        }
        if (nextSubModuleIndex < 0) {
          newSubModule = nextSubModule;
          if (moduleToSelect == null) {
            moduleToSelect = nextSubModule;
          }
        } else if (moduleToSelect == null && childModules != null) {
          moduleToSelect = childModules.get(nextSubModuleIndex);
        }
        
        if (newSubModule != null) {
          parentModule.addSubModule(newSubModule);
        }
        
        postSelectModuleObject(selectedCollection, context);
      }
      break;
    }
    
    setActionParameter(moduleToSelect, context);
    return true;
  }
}
